<template>
  <div class="container">
    <el-card shadow="never">
      <!-- 顶部标签栏 -->
      <!-- ref="queryInfoRef" -->
      <el-form :inline="true" :model="queryInfo" class="demo-form-inline">
        <el-row :gutter="20">
          <!-- 左侧搜索框 -->
          <!-- prop="subjectName" -->
          <el-col :span="18">
            <el-form-item label="学科名称">
              <el-input v-model="queryInfo.subjectName"></el-input>
            </el-form-item>

            <!-- 按钮区域 -->
            <el-form-item>
              <el-button size="small" @click="onClear">清除</el-button>
              <el-button type="primary" size="small" @click="getSubjectsList"
                >搜索</el-button
              >
            </el-form-item>
          </el-col>

          <!-- 右侧添加按钮 -->
          <el-col :span="6">
            <el-button
              class="filter-item fr"
              size="small"
              style="margin-left: 10px;"
              type="success"
              icon="el-icon-edit"
              @click="handleEdit()"
            >
              新增学科
            </el-button>
          </el-col>
        </el-row>
      </el-form>

      <!-- 数据记录 -->
      <el-alert
        :title="`数据一共 ${totalCount} 条`"
        type="info"
        show-icon
        style="margin-bottom:15px"
      ></el-alert>

      <!-- 数据列表 -->
      <el-table style="width: 100%" :data="SubjectsList">
        <el-table-column
          align="left"
          label="序号"
          prop="id"
          width="48"
          type="index"
        >
        </el-table-column>

        <el-table-column align="left" label="学科名称" prop="subjectName">
          <!-- 模板绑定数据并渲染 -->
          <template slot-scope="scope">
            <span>
              {{ scope.row.subjectName }}
            </span>
          </template>
        </el-table-column>

        <el-table-column align="left" label="创建者" prop="creator">
          <template slot-scope="scope">
            <span>
              {{ scope.row.username }}
            </span>
          </template>
        </el-table-column>

        <el-table-column
          align="left"
          label="创建日期"
          prop="addDate"
          width="160px"
        >
          <template slot-scope="scope">
            <span>
              {{ scope.row.addDate | parseTimeByString }}
            </span>
          </template>
        </el-table-column>

        <el-table-column
          align="left"
          label="前台是否显示"
          prop="isFrontDisplay"
        >
          <template slot-scope="scope">
            <span>{{ scope.row.isFrontDisplay == 1 ? '是' : '否' }}</span>
          </template>
        </el-table-column>

        <el-table-column align="left" label="二级目录" prop="twoLevelDirectory">
          <template slot-scope="scope">
            <span>
              {{ scope.row.twoLevelDirectory }}
            </span>
          </template>
        </el-table-column>

        <el-table-column align="left" label="标签" prop="tags">
          <template slot-scope="scope">
            <span>
              {{ scope.row.tags }}
            </span>
          </template>
        </el-table-column>

        <el-table-column align="left" label="题目数量" prop="totals">
          <template slot-scope="scope">
            <span>
              {{ scope.row.totals }}
            </span>
          </template>
        </el-table-column>

        <!-- 操作按钮 -->
        <el-table-column align="left" label="操作" width="249">
          <template slot-scope="scope">
            <el-button
              type="text"
              medium
              @click="
                $router.push({
                  path: 'directorys',
                  query: { id: scope.row.id, name: scope.row.subjectName }
                })
              "
              >学科分类</el-button
            >
            <el-button
              type="text"
              medium
              @click="
                $router.push({
                  path: 'tags',
                  query: { id: scope.row.id, name: scope.row.subjectName }
                })
              "
              >学科标签</el-button
            >
            <el-button type="text" medium @click="handleEdit(scope.row)"
              >修改</el-button
            >
            <el-button type="text" medium @click="handleDelete(scope.row.id)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <div class="pages">
          <el-pagination
            background
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :total="totalCount"
            :page-sizes="[5, 10, 15, 20]"
            layout=" prev,pager,next,sizes,jumper"
          ></el-pagination>
        </div>
      </div>

      <!-- 新增学科对话框 -->
    </el-card>

    <!-- 子组件会话框 -->
    <div v-if="dialogVisible">
      <subjects-add
        ref="AddSubjects"
        :titleInfo="titleInfo"
        :formBase="editId"
        @newSub="getSubjectsList"
        @open="dialogVisible = true"
        @close="handel"
      />
    </div>
  </div>
</template>

<script>
import SubjectsAdd from '../components/subjects-add'
import { list, remove } from '@/api/hmmm/subjects'

export default {
  name: 'SubjectsList',
  components: {
    SubjectsAdd
  },
  data() {
    return {
      // 定义一个空数组用来放列表数据
      SubjectsList: [],

      formInline: {
        user: ''
      },
      // 获取学科列表数据
      queryInfo: {
        // 获取过来的数据 ( 默认是 1 )
        page: 1,
        // 一页显示多少条数据 默认10条
        pagesize: 10,
        subjectName: ''
      },

      // 数据条数
      totalCount: 0,

      // 会话框标题
      titleInfo: {
        pageTitle: '学科', // 页面标题
        text: '' // 新增、编辑文本
      },

      // 传入 子组件的数据
      editId: {},

      // 控制弹窗的渲染
      dialogVisible: true
    }
  },

  created() {
    // 发起学科列表数据请求并调用函数
    this.getSubjectsList()
  },

  methods: {
    // 清除文本框内容
    onClear() {
      this.queryInfo.subjectName = ''
      // this.$refs.queryInfoRef.resetFields()
      this.getSubjectsList()
    },

    // 获取列表参数
    async getSubjectsList() {
      try {
        const { data } = await list(this.queryInfo)
        console.log(data)
        // 展示数据
        this.SubjectsList = data.items

        // 渲染数据条数
        this.totalCount = data.counts
      } catch (err) {
        this.$toast('获取数据失败，请稍后重试')
      }
    },

    // 每页显示信息条数
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)

      this.queryInfo.pagesize = val
      if (this.queryInfo.page === 1) {
        this.getSubjectsList(this.queryInfo)
      }
    },

    // 进入某一页
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)

      this.queryInfo.page = val
      this.getSubjectsList()
    },

    // 根据 id 删除学科
    async handleDelete(id) {
      console.log(id)

      // 弹框询问用户是否删除数据
      const confirmResult = await this.$confirm(
        '此操作将永久删除学科, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除！')
      }

      const { data: res } = await remove({ id })
      console.log(res)

      //! 修复删除的页面跳转BUG
      if (document.querySelectorAll('.el-card tbody tr').length === 1) {
        this.queryInfo.page =
          this.queryInfo.page > 1 ? this.queryInfo.page - 1 : 1
      }

      if (res.success) {
        this.getSubjectsList()
        return this.$message.success('删除完成')
      }
      this.$message.error('删除学科失败！')
    },

    // 根据 id 编辑学科、新增学科
    handleEdit(row) {
      // 拿到当前点击的这一行的数据
      // console.log(row)
      // 打开会话框子组件
      this.$refs.AddSubjects.open()
      // 做判断，看是编辑还是新增学科
      if (!row) {
        // 给会话框传参
        this.titleInfo.text = '新增'
        // 接收新增
        this.editId = {}
        console.log(this.editId)
      } else {
        this.titleInfo.text = '修改'
        // 接收传入的修改项
        this.editId = row
      }
    },

    // 定义的函数用来控制修改弹窗
    handel() {
      this.dialogVisible = false

      setTimeout(() => {
        this.dialogVisible = true
      }, 10)

      this.getSubjectsList()
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.text {
  font-weight: 700;
  text-align: right;
  vertical-align: middle;
  font-size: 14px;
  color: #606266;
  padding: 0 12px 0 0;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
}
.el-input--medium .el-input__inner {
  height: 32px;
  line-height: 32px;
}
.el-button--medium {
  font-size: 12px;
}
.pagination {
  margin-top: 10px;
}
.pages {
  text-align: right;
}

::v-deep.el-table td.is-center,
::v-deep.el-table th.is-center {
  text-align: left !important;
}
.el-button--medium {
  font-size: 14px;
}
</style>
